import axios, { AxiosInstance, AxiosRequestConfig } from 'axios'
import { ResponseResult } from 'types/result'

export default class {
  public instance: AxiosInstance

  constructor(config: AxiosRequestConfig) {
    this.instance = axios.create(config)

    this.interceptors()
  }

  public request<T, R = ResponseResult<T>>(config: AxiosRequestConfig) {
    return new Promise(async resolve => {
      const result = await this.instance.request<R>(config)
      resolve(result.data)
    }) as Promise<R>
  }

  private interceptors() {
    this.requestInterceptor()
    this.responseInterceptor()
  }

  private requestInterceptor() {
    this.instance.interceptors.request.use(config => {
      return config
    })
  }

  private responseInterceptor() {
    this.instance.interceptors.response.use(
      config => {
        return config
      },
      error => {
        Promise.reject(error)
      }
    )
  }
}
